const jwt = require('jsonwebtoken')
const koaJwt = require('koa-jwt')
const oneHour = 60*60*1000;

/**
 * @module 设置token
 * secret: 加密key
 * cookieKey: cookieKey 关键字
 * filePath: 非token验证地址
 * activeTime: 有效时间段, 毫秒
 * cookieConfig: cookie配置
 */
const appConfig = require('../app.config.js')
class Token{

    constructor(){
        this.config = appConfig.token;
    }

    // koa jwt 中间件, 验证过滤token是否有效
    setJwt (){
        let config = this.config;
        return koaJwt({secret:config.secret, cookie: config.cookieKey, key: config.key}).unless({
            path: config.filePath,
        })
    }

    // 创建token
    createToken (data={}){
        const tokenInfo = Object.assign({}, data, this.createTimeStamp());
        const expiresIn = this.config.activeTime / oneHour;
        return jwt.sign(tokenInfo, this.config.secret, {expiresIn:`${expiresIn}h` })
    }

    // 时间戳
    createTimeStamp(){
        const createTime = new Date();
        const createTimeSecond = createTime.getTime();
        const aeadTime = new Date();

        aeadTime.setTime(createTimeSecond + this.config.activeTime);

        return {
            createTime,
            aeadTime,
        }
        
    }

    // token绑定在cookies
    setCookies (ctx, token) {
        ctx.cookies.set(this.config.cookieKey, token, this.config.coockieConfig)
    }
    
}

module.exports = new Token();

